package com.imprenta.helpers;


import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import com.imprenta.bean.UserBean;
import com.imprenta.model.ResumenPedidoBase;
import com.imprenta.model.UsuarioBase;


public class SessionHelper {
	
	static FacesContext context = null; 
	static ExternalContext exContext = null; 
	static HttpSession session = null;
	
	private static void initHelper(){
		context = FacesContext.getCurrentInstance();
		exContext = context.getExternalContext();
		session = (HttpSession) exContext.getSession(true);
	}
	
	public static boolean createSession(String sessionName, Object sessionValue) {
		boolean isCreateSession = false;
		try {
			initHelper();
			exContext.getSessionMap().put(sessionName, sessionValue);
			isCreateSession = true;
			
		} catch (Exception e) {
			// TODO: handle exception
			isCreateSession = false;
			e.printStackTrace();			
		}
		
		return isCreateSession;
	}
	
	public static void destroySession(String sessionName){
		if (isSessionExist(sessionName)) {
			try {
				exContext.getSessionMap().remove(sessionName);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}		
	}
	
	public static boolean isSessionExist(String sessionName){
		boolean isExist = false;
		
		try {
			initHelper();
			if (session.getAttribute(sessionName) != null) {
				isExist = true;
			}
		} catch (Exception e) {
			// TODO: handle exception
			isExist = false;
		}
		
		return isExist;
	}
	
	public static UserBean getUserBeanSession(String key){
		if (isSessionExist(key)) {
			return (UserBean)exContext.getSessionMap().get(key);
		}
		return null;
	}
	
	public static ResumenPedidoBase getResumenPedidoSession(String key){
		if (isSessionExist(key)) {
			return (ResumenPedidoBase)exContext.getSessionMap().get(key);
		}
		return null;
	}
	
	public static UsuarioBase getUsuarioBase(String key){
		if (isSessionExist(key)) {
			return (UsuarioBase)exContext.getSessionMap().get(key);
		}
		return null;
	}

}
